package com.zhiwang.planet.widget

import android.content.Context
import android.graphics.Color
import androidx.annotation.DrawableRes
import androidx.appcompat.widget.AppCompatTextView
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.widget.FrameLayout
import android.widget.ImageView
import com.zhiwang.planet.R

class RankView(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    var textColor: Int = Color.BLACK

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.RankView)
        if (typedArray.hasValue(R.styleable.RankView_rank_src)) {
            setImageResource(typedArray.getResourceId(R.styleable.RankView_rank_src, 0))
        } else if (typedArray.hasValue(R.styleable.RankView_rank_text)) {
            textColor = typedArray.getColor(R.styleable.RankView_rank_text_color, Color.BLACK)
            setText(typedArray.getString(R.styleable.RankView_rank_text) ?: "")
        }
        typedArray.recycle()
    }

    fun setImageResource(@DrawableRes res: Int) {
        if (childCount == 0) {
            val imageView = ImageView(context)
            imageView.setImageResource(res)
            addView(imageView)
        } else {
            val view = getChildAt(0)
            if (view is ImageView) {
                view.setImageResource(res)
            } else {
                removeAllViews()
                setImageResource(res)
            }
        }
    }

    fun setText(text: String) {
        if (childCount == 0) {
            val textView = AppCompatTextView(context)
            textView.setTextColor(textColor)
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,18f)
            textView.text = text
            textView.gravity = Gravity.CENTER
            addView(textView)
        } else {
            val view = getChildAt(0)
            if (view is AppCompatTextView) {
                view.text = text
                view.gravity = Gravity.CENTER
                view.setTextColor(textColor)
            } else {
                removeAllViews()
                setText(text)
            }
        }
    }
}
